<script setup lang="ts">
import { delay } from "@pureadmin/utils";
import { ref, onMounted, reactive, watchEffect, h, onUnmounted } from "vue";
import {
  PaginationProps,
  LoadingConfig,
  Align,
  PureTable
} from "@pureadmin/table";
import {
  ElTag,
  ElMessage,
  ElMessageBox,
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput
} from "element-plus";
import { getDevice } from "@/api/routes";

// 数据列表和加载状态
const dataList = ref([]);
const loading = ref(true);
const tableSize = ref("default");
const paginationAlign = ref("right");

// 筛选条件
const filters = reactive({
  devId: "",
  devName: "",
  ipAddress: "",
  ipLocation: "",
  onlineStatus: "",
  firmwareVersion: "",
  appVersion: ""
});

// 多选相关状态
const selectedRows = ref([]);

// 对话框状态
const dialogVisible = ref(false);
const currentDevice = ref(null);
const commandType = ref("force_update");
const jsonCommand = ref("");

// 预设命令模板
const commandTemplates = {
  force_update: {
    template: `{
  "dev_id": "{dev_id}",
  "command": "force_update",
  "latest_app_version": "v2.0.0",
  "update_url": "https://example.com/update.zip",
  "event_time": "{current_time}"
}`,
    description: "强制设备更新到指定版本"
  },
  remote_control: {
    template: `{
  "dev_id": "{dev_id}",
  "command": "remote_control",
  "remote_command": "",
  "event_time": "{current_time}"
}`,
    description: "发送远程控制命令到设备"
  },
  set_config: {
    template: `{
  "dev_id": "{dev_id}",
  "command": "set_config",
  "config": {
    "brightness": 200,
    "volume": 70,
    "heartbeat_interval": 60,
    "city": ""
  },
  "event_time": "{current_time}"
}`,
    description: "设置设备配置参数"
  }
};

// 优化后的表格列定义
const columns = [
  {
    type: "selection",
    align: "left",
    reserveSelection: true
  },
  {
    label: "设备名称",
    prop: "dev_name",
    width: 100
  },
  {
    label: "设备ID",
    prop: "dev_id",
    width: 300
  },
  {
    label: "在线状态",
    prop: "online_status",
    width: 100,
    cellRenderer: ({ row }) => {
      return h(
        ElTag,
        {
          type: row.online_status === "在线" ? "success" : "danger",
          effect: "dark"
        },
        row.online_status
      );
    }
  },
  {
    label: "IP地址",
    prop: "ip_address",
    width: 140
  },
  {
    label: "最近活跃时间",
    prop: "last_active",
    width: 180,
    cellRenderer: ({ row }) => {
      // 将时间戳转换为可读格式
      const date = new Date(row.last_active * 1000);
      return date.toLocaleString();
    }
  },
  {
    label: "固件版本",
    prop: "firmware_version",
    width: 120
  },
  {
    label: "应用版本",
    prop: "app_version",
    width: 120
  },
  {
    label: "位置信息",
    prop: "ip_location",
    width: 150
  },
  {
    label: "操作",
    width: 120,
    cellRenderer: ({ row }) => {
      return h(
        ElButton,
        {
          type: "primary",
          size: "small",
          onClick: () => openCommandDialog(row)
        },
        () => "发送命令"
      );
    }
  }
];

/** 分页配置 */
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 20, 50],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

/** 加载动画配置 */
const loadingConfig = reactive<LoadingConfig>({
  text: "正在加载设备数据...",
  viewBox: "-10, -10, 50, 50",
  spinner: `
      <path class="path" d="
        M 30 15
        L 28 17
        M 25.61 25.61
        A 15 15, 0, 0, 0, 15 30
        A 15 15, 0, 1, 0, 27.99 7.5
        L 15 15
      " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
    `
});

// 分页大小变化
function onSizeChange(val: number) {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  loadData();
}

// 当前页变化
function onCurrentChange(val: number) {
  pagination.currentPage = val;
  loadData();
}

// 筛选方法
function applyFilters() {
  pagination.currentPage = 1;
  loadData();
}

// 重置筛选条件
function resetFilters() {
  Object.keys(filters).forEach(key => {
    filters[key] = "";
  });
  applyFilters();
}

// 批量更新方法
function batchUpdate() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要更新的设备");
    return;
  }

  ElMessageBox.confirm(
    `确定要更新选中的 ${selectedRows.value.length} 台设备吗？`,
    "确认更新",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    loading.value = true;
    // 模拟批量更新API调用
    delay(1000).then(() => {
      loading.value = false;
      ElMessage.success("更新操作已提交");
      selectedRows.value = [];
    });
  });
}

// 从后端API获取设备数据
async function fetchDeviceList() {
  try {
    const result = await getDevice();

    // 确保返回的是数组格式
    if (Array.isArray(result)) {
      return result;
    } else if (Array.isArray(result.data)) {
      return result.data;
    } else if (Array.isArray(result.result)) {
      return result.result;
    } else {
      throw new Error("API返回的数据格式不正确");
    }
  } catch (error) {
    console.error("获取设备列表失败:", error);
    ElMessage.error("获取设备列表失败");
    return [];
  }
}

// 加载数据方法
async function loadData() {
  loading.value = true;
  loadingConfig.text = `正在加载设备数据...`;

  try {
    const apiData = await fetchDeviceList();

    if (!Array.isArray(apiData)) {
      throw new Error("API返回的数据不是数组格式");
    }

    // 应用筛选条件
    const filteredData = apiData.filter(item => {
      return (
        (filters.devId ? item.dev_id.includes(filters.devId) : true) &&
        (filters.devName ? item.dev_name.includes(filters.devName) : true) &&
        (filters.ipAddress
          ? item.ip_address.includes(filters.ipAddress)
          : true) &&
        (filters.ipLocation
          ? item.dev_name.includes(filters.ipLocation)
          : true) &&
        (filters.firmwareVersion
          ? item.firmware_version.includes(filters.firmwareVersion)
          : true) &&
        (filters.appVersion
          ? item.app_version.includes(filters.appVersion)
          : true) &&
        (filters.onlineStatus
          ? filters.onlineStatus === "online"
            ? item.online_status === "在线"
            : item.online_status === "离线"
          : true)
      );
    });

    // 更新分页总数
    pagination.total = filteredData.length;

    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    dataList.value = filteredData.slice(start, end);

    console.log("加载设备数据完成", {
      total: pagination.total,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      dataCount: dataList.value.length
    });
  } catch (error) {
    console.error("加载设备数据出错:", error);
    ElMessage.error("加载设备数据失败: " + error.message);
  } finally {
    loading.value = false;
  }
}

// 打开命令对话框
function openCommandDialog(device) {
  currentDevice.value = device;
  commandType.value = "force_update";
  updateJsonCommand();
  dialogVisible.value = true;
}

// 更新JSON命令
function updateJsonCommand() {
  if (!currentDevice.value) return;

  const template = commandTemplates[commandType.value].template;
  const currentTime = new Date().toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });

  jsonCommand.value = template
    .replace(/{dev_id}/g, currentDevice.value.dev_id)
    .replace(/{current_time}/g, currentTime);
}

// 清理JSON数据，确保所有值都是可序列化的
function sanitizeJson(jsonObj: any): any {
  if (jsonObj === null || jsonObj === undefined) return "";

  if (Array.isArray(jsonObj)) {
    return jsonObj.map(item => sanitizeJson(item));
  }

  if (typeof jsonObj === "object") {
    const sanitized: Record<string, any> = {};
    for (const key in jsonObj) {
      if (Object.prototype.hasOwnProperty.call(jsonObj, key)) {
        const value = jsonObj[key];
        sanitized[key] = sanitizeJson(value);
      }
    }
    return sanitized;
  }

  // 处理原始类型
  if (typeof jsonObj === "number" || typeof jsonObj === "boolean") {
    return jsonObj;
  }

  if (typeof jsonObj === "string") {
    return jsonObj;
  }

  // 处理其他类型（如函数、symbol等）转换为字符串
  return String(jsonObj);
}

// 验证JSON格式并清理数据
function validateAndSanitizeJson(jsonStr: string): {
  valid: boolean;
  data?: any;
  error?: string;
} {
  try {
    // 解析JSON
    const jsonObj = JSON.parse(jsonStr);

    // 清理JSON数据
    const sanitizedJson = sanitizeJson(jsonObj);

    // 验证必要字段
    if (!sanitizedJson.dev_id) {
      return { valid: false, error: "缺少 dev_id 字段" };
    }

    if (!sanitizedJson.command) {
      return { valid: false, error: "缺少 command 字段" };
    }

    return { valid: true, data: sanitizedJson };
  } catch (error) {
    return { valid: false, error: "JSON格式无效: " + error.message };
  }
}

// 发送命令
function sendCommand() {
  if (!currentDevice.value) return;

  const validation = validateAndSanitizeJson(jsonCommand.value);
  if (!validation.valid) {
    ElMessage.error(validation.error || "JSON格式无效");
    return;
  }

  const ws = new WebSocket(`ws://119.45.253.56:8888/ws/frontend`);

  // 设置连接超时
  const connectionTimeout = setTimeout(() => {
    if (ws.readyState !== WebSocket.OPEN) {
      ElMessage.error("连接服务器超时");
      ws.close();
    }
  }, 5000);

  ws.onopen = () => {
    clearTimeout(connectionTimeout);

    // 确保连接已完全建立
    if (ws.readyState === WebSocket.OPEN) {
      try {
        // 添加小的延迟确保连接完全稳定
        setTimeout(() => {
          try {
            if (ws.readyState !== WebSocket.OPEN) {
              ElMessage.error("连接在发送前已关闭");
              return;
            }

            // 只发送命令部分，不包含外层包装
            ws.send(JSON.stringify(validation.data));

            ElMessage.success("命令已发送");
            dialogVisible.value = false;
          } catch (sendError) {
            console.error("发送失败:", sendError);
            ElMessage.error("命令发送失败: " + sendError.message);
          } finally {
            ws.close();
          }
        }, 100); // 100ms延迟
      } catch (error) {
        console.error("发送前准备失败:", error);
        ElMessage.error("发送准备失败: " + error.message);
        ws.close();
      }
    } else {
      ElMessage.error("连接未完全打开");
      ws.close();
    }
  };

  ws.onerror = error => {
    clearTimeout(connectionTimeout);
    console.error("WebSocket错误:", error);
    ElMessage.error("连接失败: " + error.message);
  };

  ws.onclose = event => {
    clearTimeout(connectionTimeout);
    if (!event.wasClean) {
      console.error(`连接异常关闭，代码=${event.code}，原因=${event.reason}`);
    }
  };
}

watchEffect(() => {
  pagination.align = paginationAlign.value as Align;
});

onMounted(() => {
  console.log("开始加载设备数据...");
  loadData();
});
</script>

<template>
  <div class="device-management-container">
    <!-- 优化后的筛选栏目 -->
    <el-card class="mb-4 filter-card">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="设备ID">
              <el-input
                v-model="filters.devId"
                placeholder="设备ID"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="设备名称">
              <el-input
                v-model="filters.devName"
                placeholder="设备名称"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="IP地址">
              <el-input
                v-model="filters.ipAddress"
                placeholder="IP地址"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="固件版本">
              <el-input
                v-model="filters.firmwareVersion"
                placeholder="固件版本"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="应用版本">
              <el-input
                v-model="filters.appVersion"
                placeholder="应用版本"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="状态">
              <el-select
                v-model="filters.onlineStatus"
                placeholder="全部状态"
                clearable
                class="w-full"
              >
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
            <el-form-item class="action-buttons">
              <el-button type="primary" icon="Search" @click="applyFilters">
                查询
              </el-button>
              <el-button icon="Refresh" @click="resetFilters"> 重置 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <pure-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="dataList"
        :size="tableSize"
        :pagination="pagination"
        :loadingConfig="loadingConfig"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
        @selection-change="selectedRows = $event"
      >
        <template #header>
          <div class="table-header">
            <div class="text-lg font-medium">设备列表</div>
            <div>
              <el-button
                type="primary"
                :disabled="selectedRows.length === 0"
                icon="Refresh"
                @click="batchUpdate"
              >
                更新选中设备 ({{ selectedRows.length }})
              </el-button>
            </div>
          </div>
        </template>
      </pure-table>
    </el-card>

    <!-- 命令对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`发送命令到设备 ${currentDevice?.dev_id || ''}`"
      width="800px"
    >
      <el-form label-width="100px">
        <el-form-item label="命令类型">
          <el-select v-model="commandType" @change="updateJsonCommand">
            <el-option
              v-for="(template, key) in commandTemplates"
              :key="key"
              :label="template.description"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="JSON命令">
          <el-input
            v-model="jsonCommand"
            type="textarea"
            :rows="10"
            placeholder="输入JSON命令"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendCommand">发送</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.device-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

@media (width <= 768px) {
  .el-col {
    margin-bottom: 10px;
  }

  .action-buttons {
    justify-content: center;
  }
}
</style>
